package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.service.UserBehaviorService;
import com.heima.common.constants.BehaviorConstants;
import com.heima.common.exception.CustomException;
import com.heima.common.redis.CacheService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.behavior.dtos.LikesBehaviorDto;
import com.heima.model.behavior.dtos.ReadBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.ApUserThreadLocalUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserBehaviorServiceImpl implements UserBehaviorService {
    @Autowired
    private CacheService cacheService;

    /**
     * 点赞
     *
     * @param dto
     * @return {@link ResponseResult}
     */
    @Override
    public ResponseResult likesBehavior(LikesBehaviorDto dto) {
        //数据都存在redis中的hashmap中，以(key，field，value)的形式，
        // 如key是behavior_like + articleId，field是userId，value存dto。
        //1、检查参数
        if(dto == null || String.valueOf(dto.getArticleId()) == null || checkParam(dto)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2、是否登录
        String userId = ApUserThreadLocalUtil.getUser();
        if(userId == null || Integer.parseInt(userId) == 0){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //3、点赞或取消点赞
        if(dto.getOperation() == 0){
            //点赞
            Object obj = cacheService.hGet(BehaviorConstants.LIKE_BEHAVIOR + String.valueOf(dto.getArticleId()), userId);
            if(obj != null){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, "已经点赞了");
            }
            //保存当前key
            cacheService.hPut(BehaviorConstants.LIKE_BEHAVIOR + String.valueOf(dto.getArticleId()), userId, JSON.toJSONString(dto));
        }else{
            //取消点赞，删除当前key
            cacheService.hDelete(BehaviorConstants.LIKE_BEHAVIOR + String.valueOf(dto.getArticleId()), userId);
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 阅读
     *
     * @param dto
     * @return {@link ResponseResult}
     */
    @Override
    public ResponseResult readBehavior(ReadBehaviorDto dto) {
        //参数校验
        if (dto == null || String.valueOf(dto.getArticleId()) == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.是否登录
        String userId = ApUserThreadLocalUtil.getUser();
        if (userId == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //更新阅读次数
        String readBehaviorJson = (String) cacheService.hGet(BehaviorConstants.READ_BEHAVIOR + String.valueOf(dto.getArticleId()), userId);
        if (StringUtils.isNotBlank(readBehaviorJson)) {
            ReadBehaviorDto readBehaviorDto = JSON.parseObject(readBehaviorJson, ReadBehaviorDto.class);
            dto.setCount(readBehaviorDto.getCount() + dto.getCount());
        }
        // 保存当前key
        cacheService.hPut(BehaviorConstants.READ_BEHAVIOR + String.valueOf(dto.getArticleId()), userId, JSON.toJSONString(dto));
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 检查参数
     * @param dto
     * @return
     */
    private boolean checkParam(LikesBehaviorDto dto) {
        //operation:0点赞，1取消点赞
        //type:0文章，1动态，2评论
        if(dto.getType() > 2 || dto.getType() < 0 || dto.getOperation() < 0 || dto.getOperation() > 1){
            return true;
        }
        return false;
    }
}

